import pandas as pd  
import matplotlib.pyplot as plt  
import matplotlib.dates as mdates  
plt.rcParams['font.sans-serif'] = ['GB_HT_GBT2312'] 

from Model.Sensor import *
from DAO.HDataDAO import *

def get_data_by_mongodb():
    sdd = SensorDateDAO()
    data = sdd.fetch_all()
    print(data[0:5])
    return data

def draw_pic():
    import pandas as pd
    import matplotlib.pyplot as plt
    import datetime

    data = get_data_by_mongodb()

    def extract_and_calculate_avg(data):
        df = pd.DataFrame()
        for record in data:
            time = record['time']
            for item in record['data']:
                try:
                    floor = item['device_name'].split('-')[0]
                    if floor in ['4F', '5F', '6F']:
                        humidity = float(item['humidityValue'].strip('%'))
                        temperature = float(item['temperatureValue'].strip('℃'))
                        new_df = pd.DataFrame({'floor': [floor], 'time': [time], 'humidity': [humidity], 'temperature': [temperature]})
                        df = pd.concat([df, new_df], ignore_index=True)
                except TypeError:
                    continue
        df['time'] = pd.to_datetime(df['time'])
        df = df.set_index('time')  # 这里只设置索引，不做其他操作
        avg_df = df.groupby([pd.Grouper(freq='H'), 'floor']).mean()
        return avg_df

    avg_df = extract_and_calculate_avg(data)

    # 重置索引
    avg_df = avg_df.reset_index()

    # 绘制 4 楼的图
    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx()
    ax1.plot(avg_df.loc[(avg_df['time'] >= datetime.datetime(2024, 8, 3)) & (avg_df['floor'] == '4F'), 'time'], avg_df.loc[(avg_df['time'] >= datetime.datetime(2024, 8, 3)) & (avg_df['floor'] == '4F'), 'humidity'], color='b', label='Humidity')
    ax2.plot(avg_df.loc[(avg_df['time'] >= datetime.datetime(2024, 8, 3)) & (avg_df['floor'] == '4F'), 'time'], avg_df.loc[(avg_df['time'] >= datetime.datetime(2024, 8, 3)) & (avg_df['floor'] == '4F'), 'temperature'], color='r', label='Temperature')
    ax1.set_xlabel('Time')
    ax1.set_ylabel('Humidity (%)', color='b')
    ax2.set_ylabel('Temperature (℃)', color='r')
    plt.title('4F Average Temperature and Humidity')
    plt.show()

    # 绘制 5 楼的图
    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx()
    ax1.plot(avg_df.loc[(avg_df['time'] >= datetime.datetime(2024, 8, 3)) & (avg_df['floor'] == '5F'), 'time'], avg_df.loc[(avg_df['time'] >= datetime.datetime(2024, 8, 3)) & (avg_df['floor'] == '5F'), 'humidity'], color='b', label='Humidity')
    ax2.plot(avg_df.loc[(avg_df['time'] >= datetime.datetime(2024, 8, 3)) & (avg_df['floor'] == '5F'), 'time'], avg_df.loc[(avg_df['time'] >= datetime.datetime(2024, 8, 3)) & (avg_df['floor'] == '5F'), 'temperature'], color='r', label='Temperature')
    ax1.set_xlabel('Time')
    ax1.set_ylabel('Humidity (%)', color='b')
    ax2.set_ylabel('Temperature (℃)', color='r')
    plt.title('5F Average Temperature and Humidity')
    plt.show()

    # 绘制 6 楼的图
    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx()
    ax1.plot(avg_df.loc[(avg_df['time'] >= datetime.datetime(2024, 8, 3)) & (avg_df['floor'] == '6F'), 'time'], avg_df.loc[(avg_df['time'] >= datetime.datetime(2024, 8, 3)) & (avg_df['floor'] == '6F'), 'humidity'], color='b', label='Humidity')
    ax2.plot(avg_df.loc[(avg_df['time'] >= datetime.datetime(2024, 8, 3)) & (avg_df['floor'] == '6F'), 'time'], avg_df.loc[(avg_df['time'] >= datetime.datetime(2024, 8, 3)) & (avg_df['floor'] == '6F'), 'temperature'], color='r', label='Temperature')
    ax1.set_xlabel('Time')
    ax1.set_ylabel('Humidity (%)', color='b')
    ax2.set_ylabel('Temperature (℃)', color='r')
    plt.title('6F Average Temperature and Humidity')
    plt.show()

if __name__ == '__main__':
    draw_pic()